package com.chase.champagne.data

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.chase.champagne.entity.ChampagneRecord
import org.litepal.LitePal
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap

class ChampagneRecordViewModel : ViewModel() {
    // 暂时全部取出来
    companion object {
        val liveDate: MutableLiveData<ArrayList<ChampagneRecord>> by lazy {
            MutableLiveData<ArrayList<ChampagneRecord>>().also { itAccountLiveData ->
                val accountListFromDB = LitePal.findAll(ChampagneRecord::class.java)
                itAccountLiveData.value = ArrayList(accountListFromDB)
                // itAccountLiveData.value?.forEach { Log.d("Chase", it.toString()) }
            }
        }
        private const val BASE_YEAR = 1900
    }

    private var curYear: Int = -1 // 仅在refreshOrInitRecordMonthArray()和clearCache()中更新
    private val recordMonthArray: Array<MutableMap<Int, MutableList<ChampagneRecord>>?> = arrayOfNulls(12)

    fun getLiveData() = liveDate

    fun getRecordById(id: Long): ChampagneRecord {
        return LitePal.find(ChampagneRecord::class.java, id)
    }

    fun getRecords(year: Int, month: Int, day: Int): List<ChampagneRecord> {
        return if (year == curYear && year != - 1) {
            recordMonthArray[month - 1]?.let { it[day] }?: ArrayList()
            // return liveDate.value?.filter { date == date }?:ArrayList()
        } else {
            val recordInThisYear = liveDate.value?.filter { it.date.year + BASE_YEAR == year }?:ArrayList()
            refreshOrInitRecordMonthArray(recordInThisYear)
            recordMonthArray[month - 1]?.let { it[day] }?: ArrayList()
        }
    }

    // 刷新缓存，即recordMonthArray
    fun clearCache() {
        curYear = -1
        for (i in 0 .. 11) {
            recordMonthArray[i] = null
        }
    }

    private fun refreshOrInitRecordMonthArray(recordInSameYear: List<ChampagneRecord>) {
        clearCache()
        recordInSameYear.forEach { itRecord ->
            val calendar = Calendar.getInstance()
            calendar.time = itRecord.date

            val month = calendar.get(Calendar.MONTH) + 1
            val day = calendar.get(Calendar.DATE)
            Log.d("Chase", "$month - $day")

            recordMonthArray[month - 1]?:run {recordMonthArray[month - 1] = HashMap() }
            recordMonthArray[month - 1]?.let {
                it[day]?:run { it.put(day, ArrayList()) }
                it[day]?.add(itRecord)
            }
        }
        curYear = recordInSameYear.firstOrNull()?.run { date.year + BASE_YEAR }?: -1
    }

    fun addRecord(champagneRecord: ChampagneRecord): Boolean {
        liveDate.value?.run {
            add(champagneRecord)
            liveDate.value = this
        }

        // Insert to data base
        return champagneRecord.save()
    }

    fun removeRecordById(id: Long) {
        LitePal.find(ChampagneRecord::class.java, id).delete()
        liveDate.value = ArrayList(LitePal.findAll(ChampagneRecord::class.java))
    }

    fun removeRecord(index: Int) {
        if (index < 0) {
            Log.i("Chase:RecordViewModel", "index in removeChampagneRecord() == -1")
            return
        }

        liveDate.value?.get(index)?.delete()
        liveDate.value?.run {
            removeAt(index)
            liveDate.value = this
        }
    }
}